package com.demo.ctf;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThenComposeDemo {
    public static void main(String[] args) throws Exception {
        /** 创建一个异步任务 */
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1); // 模拟耗时操作
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new IllegalStateException(e);
            }
            return "First operation result";
        });

        /** 接收future1中异步任务的运行结果 ，内部再次创建异步任务返回新的CompletableFuture*/
        CompletableFuture<String> future2 = future1.thenCompose(result1 -> {
            // 这个lambda表达式将使用future1的结果，并返回一个新的CompletableFuture
            return CompletableFuture.supplyAsync(() -> {
                try {
                    TimeUnit.SECONDS.sleep(1); // 第二个异步操作，也模拟耗时
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new IllegalStateException(e);
                }
                return "Second operation result based on " + result1;
            });
        });

        // 获取最终的异步操作结果
        String finalResult = future2.join();
        System.out.println(finalResult); // 输出: Second operation result based on First operation result
    }
}